import com.zzyl.common.Test.QianfanApiClient;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QianfanApiClient11 {

    // RestTemplate实例，实际项目中通常通过Spring注入
    private RestTemplate restTemplate;

    // API地址
    private static final String API_URL = "https://qianfan.baidubce.com/v2/chat/completions";

    // 授权令牌，替换为你的实际令牌
    private static final String AUTH_TOKEN = "bce-v3/ALTAK-FoQYI7X2oyGY98mmTmvkE/37b0a18e86dc5716f6e73608ed5a841c33adeb28";

    public QianfanApiClient11() {
        // 初始化RestTemplate
        this.restTemplate = new RestTemplate();
    }

    /**
     * 发送聊天请求到百度千帆API
     */
    public String sendChatRequest() {
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", AUTH_TOKEN);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "ernie-3.5-8k");

        // 构建messages数组
        List<Map<String, String>> messages = new ArrayList<>();

        // 添加system消息
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "平台助手");
        messages.add(systemMessage);

        // 添加user消息
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", "你好");
        messages.add(userMessage);

        requestBody.put("messages", messages);

        // 创建HTTP请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送POST请求并获取响应
            ResponseEntity<String> response = restTemplate.postForEntity(API_URL, requestEntity, String.class);

            // 检查响应状态
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                return "请求失败，状态码: " + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            return "请求发生异常: " + e.getMessage();
        }
    }

    // 示例调用方法
    public static void main(String[] args) {
        QianfanApiClient11 client = new QianfanApiClient11();
        String result = client.sendChatRequest();
        System.out.println("API响应结果: " + result);
    }
}
